package com.ly.ssh.dao.impl;

import com.ly.ssh.dao.PersonDao;
import com.ly.ssh.entity.Person;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by XRom
 * On 11/16/2017.11:55 PM
 */
@Repository
public class PersonDaoImpl implements PersonDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.openSession();
    }

    @Override
    public Person load(Integer id) {
        return (Person) getCurrentSession().load(Person.class, id);
    }

    @Override
    public Person get(Integer id) {
        return (Person) getCurrentSession().get(Person.class, id);
    }

    @Override
    public List<Person> findAll() {
        String queryString = "FROM Person";
        Query queryObject = getCurrentSession().createQuery(queryString);
        return (List<Person>)queryObject.list();
    }

    @Override
    public void persist(Person entity) {
        getCurrentSession().persist(entity);
    }

    @Override
    public Integer save(Person entity) {
        return (Integer) getCurrentSession().save(entity);
    }

    @Override
    public void saveOrUpdate(Person entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(Integer id) {
        Person person = load(id);
        getCurrentSession().delete(person);
    }

    @Override
    public void flush() {
        getCurrentSession().flush();
    }
    public List<Person> queryForPage(int offset, int length) {
        List<Person> entitylist=null;
        try{
            Query query = getCurrentSession().createQuery("FROM Person");
            query.setFirstResult(offset);
            query.setMaxResults(length);
            entitylist = query.list();

        }catch(RuntimeException re){
            throw re;
        }

        return entitylist;
    }
    public int getAllRowCount(){
            Query query = getCurrentSession().createQuery("FROM Person");

        int count = query.list().size();
        return count;
    }
}
